<?php

namespace App\Http\Controllers\Api;

use App\Common\Sms\Sms;
use App\Models\User;
use App\Services\ChatService;
use App\Services\ConfigService;
use App\Services\LoginService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

/**
 * 前台登录
 * Class LoginController
 * @package App\Http\Controllers\Api
 */
class LoginController extends Controller
{
    protected $loginService;

    public function __construct(Request $request, LoginService $loginService)
    {
        $this->loginService = $loginService;
        parent::__construct($request);
    }

    /**
     * 登录入口
     */
    public function login()
    {
        $loginType = request()->input('login_type');
        if ($this->platform == 'android' || $this->platform == 'ios') {
            if($loginType == 'oauth'){
                //app微信授权登录
                $this->loginService->loginByOauth2();
            }elseif($loginType == 'mobile&code'){
                //app手机号验证码登录
                $this->loginService->loginByMobileCode();
            }else{
                $this->error(-100,'不支持的登录方式');
            }
        } else {
            if($loginType == 'oauth'){
                //小程序授权手机号登录
                $this->loginService->loginByOauth();
            }elseif($loginType == 'mobile&code'){
                //小程序手机号验证码登录
                $this->loginService->loginByMobileCode();
            }else if($loginType == 'quiet'){
                //进入小程序静默登录
                $this->loginService->quietlyLogin();
            }else{
                $this->error(-100,'不支持的登录方式');
            }
        }
    }

    /**
     * 绑定手机号
     * @param $request
     * @throws \Exception
     */
    public function bindMobile(Request $request)
    {
        $mobile = $request->input('mobile');
        $verifyCode =  request()->input('verify_code', '');

        if (!isset($mobile)) {
            return $this->error(-100, "参数错误");
        }

//        if($verifyCode){
//            $result = Sms::checkAuthCode($verifyCode, 'bind', $mobile);
//            if(is_error($result)){
//                return $this->error($result['errno'],  $result['message']);
//            }
//        }

        $mobileUser = User::whereMobile($mobile)->first();

        /** @var User $thisUser */
        $thisUser = JWTAuth::parseToken()->authenticate();
        if($mobileUser){
            $mobileUser->openid = $thisUser->openid;
            $mobileUser->wxapp_openid = $thisUser->wxapp_openid;
            $mobileUser->unionid = $thisUser->unionid;
            $mobileUser->save();
            $thisUser->remark = "手机号已有账号，合并至{$mobileUser->id}";
            $thisUser->delete();

            JWTAuth::invalidate();

            $token = JWTAuth::fromUser($mobileUser);
            return $this->success(['token' => $token, 'userInfo' => $mobileUser]);
        }else{
            $thisUser->mobile = $mobile;
            $thisUser->save();
            return $this->success();
        }
    }

    /**
     * 获取验证码
     * @param Request $request
     */
    public function getVerifyCode(Request $request)
    {
        $type = $request->input('type');
        $mobile = $request->input('mobile');
        if (!isset($type) || !isset($mobile)) {
            return $this->error(1, "参数错误");
        }
        $code = verify_code();
        $smsClass = new Sms();
        $sendData = array('code' => $code);
        $smsConfig =  ConfigService::getSysValueByType(4);

        $ret = $smsClass->send($smsConfig, $mobile, $smsConfig['vercode_tpl'], $sendData);
        Redis::setex("sms_auth_data_{$type}_{$mobile}", 15 * 60, $code);
        return $this->success('', ’ok‘);
    }

    /**
     * 刷新token，使用以过期的token
     * 如果超过2星期没刷新，则需要重新登录
     */
    public function refreshToken()
    {
        try{
            //首先获得过期token 接着刷新token 再接着设置token并且验证token合法性
            $token = JWTAuth::refresh();

            JWTAuth::setToken($token);
            return $this->success(['token' => $token]);
        }catch (JWTException $e){
            return $this->error(401, 'token过期');
        }
    }

    /**
     * 登出
     */
    public function logout()
    {
        JWTAuth::invalidate();
        return $this->success();
    }
}
